package cn.jiangjiesheng.bootstrap.cloud.service;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import cn.jiangjiesheng.bootstrap.cloud.service.metadata.MetadataSingleton;
import cn.jiangjiesheng.bootstrap.commons.properties.DevUserMockProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.lang.Nullable;
import org.springframework.web.client.RestTemplate;

/**
 * Created by dev@jiangjiesheng.cn on 2021/8/31  <br/>
 *
 * @author dev@jiangjiesheng.cn
 */
@Configuration
@Slf4j
@ServletComponentScan(basePackages = "cn.jiangjiesheng")
@EnableConfigurationProperties({DevUserMockProperties.class, ProjectMetadataProperties.class})
public class CloudServiceAutoConfiguration {

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Bean
    @ConditionalOnMissingBean(name = "restTemplate")
    @LoadBalanced
    RestTemplate restTemplate() {
        log.info("creating load balanced restTemplate Bean.");
        return new RestTemplate();
    }

    @Nullable
    @Bean(name = "metadataSingleton")
    public MetadataSingleton metadataSingleton() {
        try {
            log.info("Bean metadataSingleton created.");
            final MetadataSingleton instance = MetadataSingleton.getInstance();
            instance.getNacosInfo().put("namespace", nacosConfigProperties.getNamespace());
            instance.getNacosInfo().put("server", nacosConfigProperties.getServerAddr());
            instance.getNacosInfo().put("sharedConfig", Joiner.on(",").join(nacosConfigProperties.getSharedConfigs()));
            return instance;
        } catch (Exception e) {
            log.error("Bean metadataSingleton created failed.", e);
            return null;
        }

    }

    @Primary
    @Bean
    public WebEndpointProperties webEndpointProperties(){
        WebEndpointProperties webEndpointProperties = new WebEndpointProperties();
        webEndpointProperties.getExposure().setExclude(Sets.newHashSet("info","mappings","metrics","env","threaddump"));
        webEndpointProperties.getExposure().setInclude(Sets.newHashSet("health"));
        return webEndpointProperties;
    }

}
